<?php

// 应用公共文件
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use think\response\Json;

function p($result)
{
    echo "<pre>";
    print_R($result);
    exit;
}

function passport_key($txt, $encrypt_key)
{
    $encrypt_key = md5($encrypt_key);
    $ctr = 0;
    $tmp = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
    }
    return $tmp;
}


function filterDate($info, $key = 'date')
{
    if ($info[$key]) {
        return date("Y-m-d", strtotime($info[$key]));
    } else {
        return date("Y-m-d", $info['updated_at']);
    }
}

// 获取x位数字随机数
function getRandNum($x)
{
    $str = '0123456789';
    $randNum = '';
    for ($i = 0; $i < $x; $i++) {
        $randNum .= $str[mt_rand(0, 9)];
    }
    return $randNum;
}

function getUserDesc($user_id)
{
    $contact_db = new \app\models\ContactModel();
    $info = $contact_db->where("id", $user_id)->field("id,name,avatar,desc")->find();
    if ($info['avatar']) {
        $info['avatar'] = env('app.host') . '/storage/' . $info['avatar'];
    } else {
        $info['avatar'] = '';
    }
    return $info;
}


function successJson($data = [], $code = 200, $info = 'success', $other = [], $header = [])
{
    return json([
        'code' => $code,
        'description' => $info,
        'data' => $data,
        'other' => $other
    ])->header($header);
}

function curlVoip($url = '', $data = [], $token = '')
{
    $data_string = json_encode($data);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $common_header[] = 'Content-Type:application/json;charset=utf-8';
    if ($token) {
        $common_header[] = 'Authorization:Bearer ' . $token;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $common_header);

    $result = curl_exec($ch);
    return $result;
}

function curlPost($url, $data = array())
{

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    // POST数据

    curl_setopt($ch, CURLOPT_POST, 1);

    // 把post的变量加上

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $output = curl_exec($ch);

    curl_close($ch);

    return $output;

}

function fileUpload($url, $post_data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_URL, $url);
    $info = curl_exec($ch);
    curl_close($ch);
    return $info;

}

// api接口统一返回格式
// api接口统一返回格式
function retJson($data = [], $code = '200', $msg = 'success')
{
    $ret['code'] = intval($code);
    $ret['data'] = $data;
    $ret['msg'] = $msg;
    return json($ret);
}

//补0方法
function dispRepair($str, $len, $msg, $type = '1')
{
    $length = $len - strlen($str);
    if ($length < 1) return $str;
    if ($type == 1) {
        $str = str_repeat($msg, $length) . $str;
    } else {
        $str .= str_repeat($msg, $length);
    }
    return $str;
}

function retError($msg = '失败', $data = [], $code = '201')
{
    $ret['code'] = intval($code);
    $ret['data'] = $data;
    $ret['msg'] = $msg;
    return json($ret);
}

function account_number()
{
    return \app\models\AccountModel::order('id', 'desc')->value('id') + 10000;
}


function retJson2($code, $info, $data = [], $other = []): Json
{
    return json([
        'code' => $code,
        'description' => $info === false ? "" : $info,
        'data' => $data,
        'other' => (object)$other
    ]);
}

// api异常统一返回格式
function retE($e, $info = '异常'): Json
{
    return retJson('303', $info, [], ['exception' => $e->getMessage()]);
}

// 对应operationRes返回的res使用
function retRes($res): Json
{
    $code = $res->isSuccess ? '200' : '400';
    $info = $res->info;

    // token失败
    if ($info == 'Get Token Failed') {
        $code = '401';
    }

    // 自定义code | other中含有 custom_code，将code改为custom_code
    if (isset($res->other->custom_code)) {
        $code = (string)$res->other->custom_code;
        unset($res->other->custom_code);
    }

    return retJson($code, $info, $res->data, $res->other);
}


// 方法之间统一返回格式，对象
function operationRes($isSuccess, $info, $data = [], $other = [])
{
    return (object)[
        'isSuccess' => $isSuccess,
        'info' => $info,
        'data' => (object)$data,
        'other' => (object)$other
    ];
}

function success($info, $data = [], $other = [])
{
    return (object)[
        'isSuccess' => true,
        'info' => $info,
        'data' => (object)$data,
        'other' => (object)$other
    ];
}

function fail($info, $data = [], $other = [])
{
    return (object)[
        'isSuccess' => false,
        'info' => $info,
        'data' => (object)$data,
        'other' => (object)$other
    ];
}

// 参数格式错误
function retErrParam($info = 'Parameter Format Error', $code = 400): Json
{
    return retJson([], $code, $info);
}

function mylog($message, $name = 'name')
{

    $log = new Logger($name);
    try {
        $log->pushHandler(new StreamHandler(root_path() . 'my.log', Logger::INFO));
    } catch (Exception $e) {
        echo($e->getMessage());
    }
    $log->info(json_encode($message));


}


function change_to_quotes($str)
{
    return sprintf("'%s'", $str);
}

function getTrueOrFalse($status)
{
    if ($status == 1) {
        return true;
    } else {
        return false;
    }
}

function getTree($row)
{
    $tmp['path'] = $row['path'];
    $tmp['component'] = $row['component'];
    $tmp['name'] = $row['name'];
    $tmp['id'] = $row['id'];
    $tmp['parent_id'] = $row['parent_id'];
    $tmp['meta'] = [
        'title' => $row['title'],
        'icon' => $row['icon'],
        'sorts' => $row['sorts'],
        'levelHidden' => getTrueOrFalse($row['levelHidden']),
        'hidden' => getTrueOrFalse($row['hidden']),
        'dynamicNewTab' => getTrueOrFalse($row['dynamicNewTab']),
//        'noKeepAlive'=>getTrueOrFalse($row['noKeepAlive']),
        'noClosable' => getTrueOrFalse($row['noClosable']),
//        'badge'=>$row['badge'],
//        'dot'=>getTrueOrFalse($row['dot']),
        'breadcrumbHidden' => getTrueOrFalse($row['breadcrumbHidden']),
    ];

    return $tmp;
}


// 获取一级
function getSons($categorys, $catId = 0)
{
    $sons = array();
    foreach ($categorys as $item) {
        if ($item['pid'] == $catId)
            $sons[] = $item;
    }
    return $sons;
}

//获取子级
function getSubs($categorys, $catId = 0, $level = 1)
{
    $subs = array();
    foreach ($categorys as $item) {
        if ($item['pid'] == $catId) {
            $item['level'] = $level;
            $subs[] = $item;
            $subs = array_merge($subs, getSubs($categorys, $item['id'], $level + 1));

        }

    }
    return $subs;
}


//获取父级列表
function getParents($categorys, $catId)
{
    $tree = array();
    foreach ($categorys as $item) {
        if ($item['id'] == $catId) {
            if ($item['pid'] > 0)
                $tree = array_merge($tree, getParents($categorys, $item['pid']));
            $tree[] = $item;
            break;
        }
    }
    return $tree;
}

function getParentsByKey($categorys, $catId, $key)
{
    $tree = array();
    foreach ($categorys as $item) {
        if ($item[$key] == $catId) {
            if ($item['pid'] > 0)
                $tree = array_merge($tree, getParents($categorys, $item['pid']));
            $tree[] = $item;
            break;
        }
    }
    return $tree;
}


//获取无限级分类
function getChild($data, $id = 0)
{
    //初始化儿子
    $child = [];
    //循环所有数据找$id的儿子
    foreach ($data as $key => $datum) {
        //找到儿子了
        if ($datum['pid'] == $id) {
            //保存下来，然后继续找儿子的儿子
            $child[$datum['id']] = $datum;
            //先去掉自己，自己不可能是自己的儿孙
            unset($data[$key]);
            //递归找，并把找到的儿子放到一个child的字段中
            $child[$datum['id']]['children'] = array_values(getChild($data, $datum['id']));
        }
    }
    return $child;
}


function getTypeFlag($result)
{
    $flag = 3;
    if ($result) {
        if ($result[0]['icon']) {
            $flag = 1;
        }
        if ($result[0]['banner']) {
            $flag = 2;
        }
    }
    return $flag;
}


//二维数组排序
function arraySort($arr, $keys, $type = 'asc')
{
    $keysvalue = $new_array = array();

    //方式1【推荐】
    $keysvalue = array_column($arr, $keys, NULL);//将目标字段单独提取出来生成一个一维数组
    //方式2
    foreach ($arr as $k => $v) { //遍历生成
        $keysvalue[$k] = $v[$keys];
    }

    $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);//排序键名不变
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

function sendCurlPostRequest($url, $postData)
{
    $curl = curl_init($url);

    // 将数组转换为 JSON 字符串
    $jsonEncodedData = json_encode($postData);

    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $jsonEncodedData, // 使用 JSON 字符串
        CURLOPT_HTTPHEADER => array(
            'User-Agent: Apifox/1.0.0 (https://apifox.com)',
            'Content-Type: application/json'
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        return false;
    } else {
        return $response;
    }
}
